package com.juphoon.oauth.core.config;

import com.juphoon.oauth.core.listener.AuthenticationListener;
import com.juphoon.oauth.core.service.DefaultUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.servlet.http.HttpServletRequest;

/**
 * @author rongbin.huang
 */
@Configuration
@Slf4j
public class OAuthSecurityBeanConfig {

    @Bean
    @ConditionalOnMissingBean(PasswordEncoder.class)
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    @ConditionalOnMissingBean(UserDetailsService.class)
    public UserDetailsService userDetailsService() {
        return new DefaultUserServiceImpl();
    }

    @Bean
    @ConditionalOnMissingBean(AuthenticationListener.class)
    public AuthenticationListener authenticationListener() {
        return new AuthenticationListener() {

            @Override
            public void loginSuccess(HttpServletRequest request, Object principal, String accessToken) {
                log.info("login success");
            }

            @Override
            public void loginFail(HttpServletRequest request, Exception exception) {
                log.error("error", exception);
            }

            @Override
            public void logout(HttpServletRequest request) {
                log.info("logout");
            }

            @Override
            public void refreshToken(HttpServletRequest request, String accessToken) {
                log.info("refreshToken {}", accessToken);
            }
        };
    }

}
